/**
 * Created by sicongdu on 17-11-3.
 */

const express = require('express');
var minihabit = express.Router();


var err = {
  error_no: 2,
  error_msg: "内部错误，请联系杜思聪～"
}

//get list of minihabits
minihabit.post("/minihabits", function (req, res, next) {
  var find_minihabits_by_openid = (openid, res, doc = {}) => {
    var minihabits = require("./minihabit_model").minihabits
    minihabits.find({
      openid: openid
    }).sort({'_id': 1}).exec((error, documents) => {
      if (error) {
        res.send(err)
      } else {
        res.send({
          error_no: 0,
          error_msg: "ok",
          minihabits: documents
        })
      }
    })
  }

  var getOpenId = require("../login/getOpenId").getOpenId
  getOpenId(req.body.code, find_minihabits_by_openid, res, {}, 2)

});

//create a minihabit
minihabit.post("/new_minihabit", function (req, res, next) {
  var create_minihabit = (openid, res, doc = {}) => {
    var minihabits = require("./minihabit_model").minihabits
    minihabits.create({
      name: req.body.name,
      detail: req.body.detail,
      time_way: req.body.time_way,
      start_time: req.body.start_time,
      stop_time: req.body.stop_time,
      select_weekday: req.body.select_weekday,
      openid: openid,
      times: 0,
      last_day: "",
      hint: true
    }, (error, doc) => {
      if (error) {
        res.send(err)
      } else {
        res.send({
          error_no: 0,
          error_msg: "ok",
          minihabit: doc
        })
      }
    })
  }

  var getOpenId = require("../login/getOpenId").getOpenId
  getOpenId(req.body.code, create_minihabit, res, {}, 2)

});

//update a minihabit
minihabit.post("/update", function (req, res, next) {
  var minihabits = require("./minihabit_model").minihabits
  minihabits.update({
    _id: req.body._id
  }, {
    $set: {
      name: req.body.name,
      detail: req.body.detail,
      time_way: req.body.time_way,
      start_time: req.body.start_time,
      stop_time: req.body.stop_time,
      select_weekday: req.body.select_weekday
    }
  }, (error, doc) => {
    if (error) {
      res.send(err)
    } else {
      res.send({
        error_no: 0,
        error_msg: "ok",
        minihabit: doc
      })
    }
  })


});

//打卡
minihabit.post("/daka", function (req, res, next) {
	/*var date = new Date();
	var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
      
    var currentdate = year + seperator1 + month + seperator1 + strDate;
*/

  var minihabits = require("./minihabit_model").minihabits
  minihabits.update({
    _id: req.body._id,
  }, {
    $inc: {'times': 1},
    last_day: req.body.last_day,
    $addToSet: { 'history': req.body.last_day} 
  }, (error, documents) => {
    if (error) {
      res.send(err)
    } else {
      res.send({
        error_no: 0,
        error_msg: "ok",
        minihabits: documents
      })
    }
  })
});

//删除微习惯
minihabit.post("/delete", function (req, res, next) {

  var minihabits = require("./minihabit_model").minihabits
  minihabits.remove({
    _id: req.body._id,
  }, (error, documents) => {
    if (error) {
      res.send(err)
    } else {
      res.send({
        error_no: 0,
        error_msg: "ok",
        minihabits: documents
      })
    }
  })
});

//设置是否提醒
minihabit.post("/hint", function (req, res, next) {

  var minihabits = require("./minihabit_model").minihabits
  minihabits.update({
    _id: req.body._id,
  }, {
    $set: {
      hint: req.body.hint
    }
  }, (error, documents) => {
    if (error) {
      res.send(err)
      return
    } else {
      res.send({
        error_no: 0,
        error_msg: "ok",
        minihabits: documents
      })
    }
  })
});

//获取详情
minihabit.post("/get_minihabit_details", function (req, res, next) {

  var minihabits = require("./minihabit_model").minihabits
  minihabits.findOne({
    _id: req.body._id,
  }, (error, documents) => {
    if (error) {
      res.send(err)
    } else {
      res.send({
        error_no: 0,
        error_msg: "ok",
        minihabit: documents
      })
    }
  })
});


//查询一周内打卡记录
minihabit.post("/one_week_record", function (req, res, next) {
	
	var find_minihabits_by_openid = (openid, res, doc = {}) => {
	var minihabits = require("./minihabit_model").minihabits
	minihabits.find({
			openid: openid// '233'
		
		},{history: 1, name: 1},
			(error, documents) => {
    		if (error) {
      			res.send(err)
    		} else {
    			console.log(documents);
    			 
    			
    			function getWeek(i) {
					var now = new Date();
					var firstDay=new Date(now - (now .getDay() - 1 ) * 86400000);
					firstDay.setDate(firstDay.getDate() + i);
					var mon = Number(firstDay.getMonth()) + 1;
					return now .getFullYear() + "-" + mon + "-" + firstDay.getDate();
				}
				
				var thisWeek = [getWeek(0), getWeek(1), getWeek(2), getWeek(3), getWeek(4),getWeek(5),getWeek(6)];
				//console.log(thisWeek);
    			
    			var this_week_result = new Array();
    			
    			for(var i=0; i < documents.length; i++){
    				var dates = new Array();
    				var temp_one = new Object();
    							
    				//traverse every element of history of each minihabit
    				if(Array.isArray(documents[i].history)){ 				
    					documents[i].history.forEach((value) => {	
    						if(thisWeek.indexOf(value) >= 0){						
    							dates.push(value);
    						}
   						});
    					
    					temp_one.name = documents[i].name;						
    					temp_one.dates = dates;
    					this_week_result[i] = temp_one;
    					console.log(this_week_result);				
    				}
    			}
      			res.send({
        			error_no: 0,
        			error_msg: "ok",
        			minihabit: documents,
        			result: this_week_result
      			})
    		}
  		})
  		
  	}
  	
  	 var getOpenId = require("../login/getOpenId").getOpenId
  	 getOpenId(req.body.code, find_minihabits_by_openid, res, {}, 2)
});

minihabit.post("/all_record", function (req, res, next) {
	var find_minihabits_by_openid = (openid, res, doc = {}) => {
	
	var minihabits = require("./minihabit_model").minihabits
	minihabits.find({
			openid: openid
		},{history: 1, name: 1},
			(error, documents) => {
    		if (error) {
      			res.send(err)
    		} else {
    			var all_result = new Array();
    			
    			for(var i=0; i < documents.length; i++){
    				var dates = new Array();
    				var temp_one = new Object();
    							
    				//traverse every element of history of each minihabit
    				if(Array.isArray(documents[i].history)){ 				
    					documents[i].history.forEach((value) => {	
    										
    							dates.push(value);
    						
   						});
    					
    					temp_one.name = documents[i].name;						
    					temp_one.dates = dates;
    					all_result[i] = temp_one;
    					console.log(all_result);				
    				}
    			}
      			res.send({
        			error_no: 0,
        			error_msg: "ok",
        			minihabit: documents,
        			result: all_result
      			})
    		}
  		})
  	}
  	var getOpenId = require("../login/getOpenId").getOpenId
  	 getOpenId(req.body.code, find_minihabits_by_openid, res, {}, 2)
});

module.exports = minihabit;
